﻿function BindListItem(model) {
    var self = this;
    self.Id = model.Id;
    self.RequestUserName = model.RequestUserName;
    self.Description = model.Description;
    self.Status = model.Status;
    self.CreateDate = model.CreateDate;
    self.Phone = model.Phone;
    self.Mobile = model.Mobile;
    self.Project = model.Project;
    self.LeaderName = model.LeaderName;
    self.Department = model.Department;

    self.ZipFileUrl = ko.observable(model.ZipFileUrl);
    self.ShowFileUrl = ko.observable(model.ShowFileUrl);
    self.ShowProgressIcon = ko.observable(model.ShowProgressIcon);
    self.ShowErrorMessage = model.ShowErrorMessage;
    self.ErrorMessage = ko.observable(model.ErrorMessage);
    self.ShowApproveButton = ko.observable(model.ShowApproveButton);
    self.ShowDownloadButton = ko.observable(model.ShowDownloadButton);
}

function ViewModel(options) {
    var self = this;

    //标题、数据集、弹出对话框和内容（HTML）
    self.title = ko.observable(options.title);
    self.recordSet = ko.observableArray();
    self.dialogContent = ko.observable();
    self.dialog = options.dialogId ? $("#" + options.dialogId) : $("#dialog");

    //排序
    //orderBy，defaultOrderBy & isAsc: 当前排序字段名，默认排序字段名和方向（升序/降序）
    //totalPages， pageNumbers & pageIndex：总页数，页码列表和当前页
    self.orderBy = ko.observable();
    self.isAsc = ko.observable();
    self.defaultOrderBy = options.defaultOrderBy;
    
    self.needResetPwd = ko.observable(options.needShowPwdLink),

    //分页
    //totalPages， pageNumbers & pageIndex：总页数，页码列表和当前页
    self.totalPages = ko.observable();
    self.pageNumbers = ko.observableArray();
    self.pageIndex = ko.observable();

    //查询条件：标签和输入值
    self.searchCriteria = ko.observableArray(options.searchCriteria);

    //作为显示数据的表格的头部：显示文字和对应的字段名（辅助排序）
    self.headers = ko.observableArray(options.headers);

    //CRUD均通过Ajax调用实现，这里提供用于获取Ajax请求地址的方法
    self.dataQueryUrlAccessor = options.dataQueryUrlAccessor;
    self.dataApproveAccessor = options.dataApproveAccessor;
    self.dataRejectAccessor = options.dataRejectAccessor;
    self.dataDeleteAccessor = options.dataDeleteAccessor;
    self.dataAddUrlAccessor = options.dataAddUrlAccessor;
    self.dataUpdateAccessor = options.dataUpdateAccessor;
    self.dataDownloadAccessor = options.dataDownloadAccessor;
    
    //removeData：删除操作完成后将数据从recordSet中移除
    //replaceData：修改操作后更新recordSet中相应记录
    self.removeData = options.removeData;
    self.replaceData = options.replaceData;

    //Search按钮
    self.search = function () {
        self.orderBy(self.defaultOrderBy);
        self.isAsc(false);
        self.pageIndex(1);
        $.ajax(
        {
            url: self.dataQueryUrlAccessor(self),
            type: "GET",
            success: function (result) {
                var newArray = new Array();
                if (result.Data != null) {
                    for (var i = 0; i < result.Data.length; i++) {
                        newArray.push(new BindListItem(result.Data[i]));
                    }
                }
                self.recordSet(newArray);
                self.totalPages(result.TotalPages);
                self.resetPageNumbders();
            }
        });
    };

    //Reset按钮
    self.reset = function () {
        for (var i = 0; i < self.searchCriteria().length; i++) {
            self.searchCriteria()[i].value("");
            self.search();
        }
    };

    //获取数据之后根据记录数重置页码
    self.resetPageNumbders = function () {
        self.pageNumbers.removeAll();
        for (var i = 1; i <= self.totalPages() ; i++) {
            self.pageNumbers.push(i);
        }
    };

    //点击表格头部进行排序
    self.sort = function (header) {
        if (header.canOrder == "false") {
            return;
        }
        if (self.orderBy() == header.value) {
            self.isAsc(!self.isAsc());
        }
        self.orderBy(header.value);
        self.pageIndex(1);
        $.ajax(
        {
            url: self.dataQueryUrlAccessor(self),
            type: "GET",
            success: function (result) {
                self.recordSet(result.Data);
            }
        });
    };

    //点击页码获取当前页数据
    self.turnPage = function (pageIndex) {
        self.pageIndex(pageIndex);
        $.ajax(
        {
            url: self.dataQueryUrlAccessor(self),
            type: "GET",
            success: function (result) {
                self.recordSet(result.Data);
            }
        });
    };
    
    //点击Add按钮弹出“添加数据”对话框
    self.onDataAdding = function () {
        $.ajax(
        {
            url: self.dataAddUrlAccessor(self),
            type: "GET",
            success: function (result) {
                self.dialogContent(result);
                self.dialog.modal("show");
            }
        });
    };

    //点击“添加数据”对话框的Save按钮关闭对话框，并将添加的记录插入recordSet
    self.onDataAdded = function (data) {
        $("#labelError").text("");
        if (data.IsValid == true) {
            self.dialog.modal("hide");
            self.recordSet.unshift(data);
        } else {
            if (data.ErrorMessage == null) {
                data.ErrorMessage = "System Error, please contact administrator!";
            }
            $("#labelError").text(data.ErrorMessage);
            alert(data.ErrorMessage);
        }
    };
    
    //点击Update按钮弹出“修改数据”对话框
    self.onDataUpdating = function (data) {
        $.ajax(
        {
            url: self.dataUpdateAccessor(data, self),
            type: "GET",
            success: function (result) {
                self.dialogContent(result);
                self.dialog.modal("show");
            }
        });
    };

    //点击“修改数据”对话框的Save按钮关闭对话框，并修改recordSet中的数据
    self.onDataUpdated = function (data) {
        self.dialog.modal("hide");
        self.replaceData(data, self);
    };

    //点击Update按钮弹出“修改数据”对话框
    self.onDataApproving = function (data) {
        data.ShowProgressIcon(true);
        data.ShowFileUrl(false);
        $.ajax(
        {
            url: self.dataApproveAccessor(data, self),
            type: "GET",
            success: function (result) {
                var item = new BindListItem(result);
                self.replaceData(item, self);
            },
            error: function () {
                // 并显示对应的错误消息。
                self.showErrorMessage(true);
            }
        });
    };

    //点击Update按钮弹出“修改数据”对话框
    self.onDataDownload = function (data) {
        data.ShowProgressIcon(true);
        data.ShowFileUrl(false);
        $.ajax(
        {
            url: self.dataDownloadAccessor(data, self),
            type: "GET",
            success: function (result) {
                var item = new BindListItem(result);
                self.replaceData(item, self);
            },
            error: function () {
                // 并显示对应的错误消息。
                self.showErrorMessage(true);
            }
        });
    };
    
    //点击Delete按钮删除当前记录
    self.onDataRejecting = function (data) {
        var confirmResult = confirm("Are you sure you want to Reject current record?");
        if (confirmResult != true)
            return;
        $.ajax(
        {
            url: self.dataRejectAccessor(data, self),
            type: "GET",
            success: function (result) {
                var item = new BindListItem(result);
                self.removeData(item, self);
            }
        });
    };
    
    //点击Delete按钮删除当前记录
    self.onDataDeleting = function (data) {
        var confirmResult = confirm("Are you sure you want to delete current record?");
        if (confirmResult != true)
            return;
        $.ajax(
        {
            url: self.dataDeleteAccessor(data, self),
            type: "GET",
            success: function (result) {
                var item = new BindListItem(result);
                self.removeData(item, self);
            }
        });
    };
    
    self.search();
}